<?php

namespace App\Helpers;
use App\Models\PreDzlabQwenGroup;
use App\Models\PreDzlabQwenGroupUser;
use App\Models\PreDzlabQwenPack;
use Illuminate\Support\Facades\DB;

class AiPackChatHelper
{
    /**
     * 获取支付信息
     * @param $uid
     * @param $isPlus
     * @param $default
     * @return array
     */
    public static function getPayInfo($uid,$isPlus,$default)
    {
        $now = now()->timestamp;
        $pack = PreDzlabQwenPack::query()
            ->where('uid',$uid)
            ->where('type',$isPlus)
            ->where('expire_at','>',$now)
            ->first();
        if($pack){
            return ['pack'=>'self','ext'=>0];
        }
        $groupUser = PreDzlabQwenGroupUser::find($uid);
        if(!$groupUser){
            return ['pack'=>'none','ext'=>$default];
        }
        $group = $groupUser->group;
        if(!$group || $group['deadline'] < $now){
            return ['pack'=>'none','ext'=>$default];
        }
        if($group['surplus_num_'.$isPlus] <= 0){
            return ['pack'=>'none','ext'=>$default];
        }
        if($groupUser['surplus_num_'.$isPlus]<= 0)
        {
            return ['pack'=>'none','ext'=>$default];
        }
        return ['pack'=>'group','ext'=>0];
    }

    public static function decrementUserNum($uid, $version)
    {
        // 使用Eloquent模型查询有效套餐
        $pack = PreDzlabQwenPack::query()
            ->where('uid', $uid)
            ->where('surplus_num', '>', 0)
            ->where('type', $version)
            ->where('expire_at', '>', now()->timestamp)
            ->first();

        // 如果找到有效套餐，则减少剩余次数并增加已用次数
        if ($pack) {
            $pack->update([
                'surplus_num' => $pack->surplus_num - 1,
                'uesd_num' => $pack->uesd_num + 1  // 注意：原代码中可能存在拼写错误，应该是used_num
            ]);
        }
    }
    public static function decrementGroupNum($group_id, $version)
    {
        // 使用Eloquent模型更新群组剩余次数和已用次数
        PreDzlabQwenGroup::where('id', $group_id)
            ->update([
                "surplus_num_{$version}" => DB::raw("surplus_num_{$version} - 1"),
                "used_num_{$version}" => DB::raw("used_num_{$version} + 1")
            ]);
    }

    public static function decrementGroupNumByUid($uid, $version)
    {
        // 获取用户所属群组ID
        $groupUser = PreDzlabQwenGroupUser::where('uid', $uid)->first();

        if (!$groupUser) {
            return;
        }
        $group_id = $groupUser->group_id;
        // 更新群组的剩余次数和已用次数
        PreDzlabQwenGroup::where('id', $group_id)
            ->update([
                "surplus_num_{$version}" => DB::raw("surplus_num_{$version} - 1"),
                "used_num_{$version}" => DB::raw("used_num_{$version} + 1")
            ]);

        // 更新用户的剩余次数和已用次数
        $groupUser->update([
            "surplus_num_{$version}" => DB::raw("surplus_num_{$version} - 1"),
            "use_num_{$version}" => DB::raw("use_num_{$version} + 1")
        ]);
    }
}
